package com.mediacloud.app.newsmodule.activity.audio

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.mediacloud.app.assembly.util.StringUtils
import com.mediacloud.app.assembly.util.jsonToArrayList
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.model.PageRecord
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.view.XSmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.empty_content.*
import org.jetbrains.anko.backgroundColor
import org.json.JSONObject


/**
 * 主播作品集
 */
class AudioAnchorWorksActivity : BaseBackActivity(), OnRefreshLoadMoreListener, OnClickListener {

    private var llTitleBar: LinearLayout? = null
    private var ivBack: ImageView? = null
    private var ivBarIcon: ImageView? = null
    private var tvBarName: TextView? = null
    private var scrollView: NestedScrollView? = null
    private var ivIcon: ImageView? = null
    private var tvName: TextView? = null
    private var tvNum: TextView? = null
    private var refresh: XSmartRefreshLayout? = null
    private var recyclerView: RecyclerView? = null
    private var rlEmptyView: ConstraintLayout? = null
    private var rvAdapter: AudioAnchorWorksListAdapter? = null
    private var pageNum = 1
    private var pageSize = 20
    private var listData: ArrayList<PageRecord>? = null
    private var anchorId: String? = null
    private var anchorName: String? = null
    private var anchorAvatar: String? = null
    private var anchorPlayCount: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initData()
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_audio_anchor_works
    }

    fun initView() {
        llTitleBar = findViewById(R.id.ll_audio_anchor_title_bar)
        ivBack = findViewById(R.id.iv_audio_anchor_title_bar_back)
        ivBarIcon = findViewById(R.id.iv_audio_anchor_title_bar_profile)
        tvBarName = findViewById(R.id.tv_audio_anchor_title_bar_name)
        scrollView = findViewById(R.id.sv_audio_anchor_works)
        ivIcon = findViewById(R.id.iv_audio_anchor_introduction_profile)
        tvName = findViewById(R.id.tv_audio_anchor_introduction_name)
        tvNum = findViewById(R.id.tv_audio_anchor_introduction_num)
        refresh = findViewById(R.id.refresh_audio_anchor_works_list)
        recyclerView = findViewById(R.id.rv_audio_anchor_works_list)
        rlEmptyView = findViewById(R.id.layout_common_no_view)

        anchorId = intent.getStringExtra("anchorId")
        anchorName = intent.getStringExtra("anchorName")
        anchorAvatar = intent.getStringExtra("anchorAvatar")
        anchorPlayCount = intent.getStringExtra("anchorPlayCount")
        setCommonData()

        refresh?.setOnRefreshLoadMoreListener(this)
        ivBack?.setOnClickListener(this)
        ivBarIcon?.setOnClickListener(this)
        tvBarName?.setOnClickListener(this)

        recyclerView?.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this, true)
        rvAdapter = AudioAnchorWorksListAdapter()
        recyclerView?.adapter = rvAdapter

        scrollView?.setOnScrollChangeListener { view, i, i1, i2, i3 ->
            if (i1 > 400) {
                llTitleBar?.backgroundColor = Color.WHITE
                ivBarIcon?.visibility = View.VISIBLE
                tvBarName?.visibility = View.VISIBLE
            } else {
                llTitleBar?.backgroundColor = Color.parseColor("#FDF5F4")
                ivBarIcon?.visibility = View.GONE
                tvBarName?.visibility = View.GONE
            }
        }
    }

    fun initData() {
        val map: MutableMap<String, String> = HashMap()
        map["pageNumber"] = "$pageNum"
        map["pageSize"] = "$pageSize"
        map["anchorId"] = "$anchorId"
        DataInvokeUtil.getZiMeiTiApi()
            .getAnchorWorkList(map)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(t: JSONObject) {
                    try {
                        refresh?.finishRefresh()
                        val data = t.optJSONObject("data")
                        if (data != null) {
                            val meta = data.optJSONArray("PageRecord")
                            if (meta != null) {
                                listData = jsonToArrayList(
                                    meta.toString(),
                                    PageRecord::class.java
                                )
                                if (pageNum == 1) {
                                    if (listData?.size!! <= 0) {
                                        emptyTipsText?.text = "暂无作品"
                                        rlEmptyView?.visibility = View.VISIBLE
                                        showStateView(TYPE_NO_CONTENT, false)
                                    } else {
                                        closeStateView()
                                        rlEmptyView?.visibility = View.GONE
                                        emptyTipsText?.visibility = View.GONE
                                        rvAdapter?.setNewData(listData!!)
                                    }
                                } else {
                                    rvAdapter?.addData(listData!!)
                                }
                                rvAdapter?.notifyItemRangeChanged(0, rvAdapter?.itemCount!!)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onError(e: Throwable) {
                    emptyTipsText?.text = "暂无作品"
                    rlEmptyView?.visibility = View.GONE
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }

                override fun onComplete() {}

            })
    }

    private fun setCommonData() {
        val options = RequestOptions()
            .placeholder(R.drawable.user_default_icon)
            .error(R.drawable.user_default_icon)
        Glide.with(this@AudioAnchorWorksActivity)
            .load(anchorAvatar)
            .apply(options)
            .into(ivBarIcon!!)
        Glide.with(this@AudioAnchorWorksActivity)
            .load(anchorAvatar)
            .apply(options)
            .into(ivIcon!!)
        tvBarName?.text = anchorName
        tvName?.text = anchorName
        tvNum?.text = "作品累计播放量："+ StringUtils.toTenThousand(anchorPlayCount)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        pageNum = 1
        initData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        pageNum++
        initData()
    }

    override fun onClick(v: View?) {
        val id = v?.id
        if (id == R.id.iv_audio_anchor_title_bar_back) {
            finish()
        }
    }

    override fun getFitSystemWindow() = false

    override fun getStatusBarColor() = Color.TRANSPARENT
}